Skip to content

Latest commit

 

History

History
56 lines (42 loc) · 2.06 KB

File metadata and controls

56 lines (42 loc) · 2.06 KB

1849. Splitting a String Into Descending Consecutive Values

You are given a string s that consists of only digits.

Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1.

  • For example, the string s = "0090089" can be split into ["0090", "089"] with numerical values [90,89]. The values are in descending order and adjacent values differ by 1, so this way is valid.
  • Another example, the string s = "001" can be split into ["0", "01"], ["00", "1"], or ["0", "0", "1"]. However all the ways are invalid because they have numerical values [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order.

Return trueif it is possible to splitsas described above, orfalseotherwise.

A substring is a contiguous sequence of characters in a string.

Example 1:

Input: s = "1234" Output: false Explanation: There is no valid way to split s. 

Example 2:

Input: s = "050043" Output: true Explanation: s can be split into ["05", "004", "3"] with numerical values [5,4,3]. The values are in descending order with adjacent values differing by 1. 

Example 3:

Input: s = "9080701" Output: false Explanation: There is no valid way to split s. 

Constraints:

  • 1 <= s.length <= 20
  • s only consists of digits.

Solutions (Python)

1. Solution

fromfunctoolsimportcacheclassSolution: @cachedefsplitString(self, s: str, x: int=None) ->bool: ifxisNone: returnany(self.splitString(s[i:], int(s[:i])) foriinrange(1, len(s))) ifs=="": returnTruereturnany(x-1==int(s[:i]) andself.splitString(s[i:], int(s[:i])) foriinrange(1, len(s) +1))
close